import { createRouter, createWebHashHistory } from 'vue-router'
import routes from './routes'
import { getToken } from '@/utils/userManage'
import { $warn } from '@/utils/functions'
import { setUnlLoginPage } from '@/utils/buffer'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    ...routes,
    { // 错误路由重定向
      path: '/:pathMatch(.*)*',
      redirect: '/'
    }
  ]
})

/**
 * 路由拦截
 */
router.beforeEach((to, from, next) => {
  /* 需要登录，但是没有token */
  if (to.meta.needLogin && !getToken()) {
    setUnlLoginPage({
      name: to.name,
      params: to.params,
      query: to.query
    })
    $warn('请先登录')
    next({ name: 'Login' })
  } else {
    next()
  }
  window.scrollTo(0, 0)
})

export default router
